﻿using MJankowski.org.AutoMock.MockFactories;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MJankowski.org.AutoMock
{
    public class AutoMoq<TTargetType> : AutoMock<TTargetType> where TTargetType : class
    {
        public AutoMoq()
            : base(new MoqMockingFactory())
        {
        }

        /// <summary>
        /// Sets dependencies to be injected while building TTargetType.
        /// </summary>
        public AutoMoq(DependencyContainer dependencyContainer)
            : base(new MoqMockingFactory(), dependencyContainer)
        {
        }

        public Mock<T> GetMock<T>() where T : class
        {
            return GetMockFromObject(base.GetMock<T>());
        }

        public static Mock<T> GetMockFromObject<T>(T mockedObject) where T : class
        {
            PropertyInfo[] pis = mockedObject.GetType().GetProperties()
                .Where(
                    p => p.PropertyType.Name == "Mock`1"
                ).ToArray();
            return pis.First().GetGetMethod().Invoke(mockedObject, null) as Mock<T>;
        }
    }
}
